<?php
/**
 * Created by PhpStorm.
 * User: wumengmeng <wu_mengmeng@foxmail.com>
 * Date: 2019/4/26 0026
 * Time: 14:35
 */

namespace HiCommon\Service;

use HiCommon\Repository\AdminsRepository;
use HiCommon\Repository\CheckpointMakeDateRepository;
use HiCommon\Repository\CheckpointRepository;
use HiCommon\Repository\CheckpointServiceTypeRepository;
use HiCommon\Repository\CheckpointTypeRepository;

class CheckpointService extends BaseService
{
    /**
     * 检测机构详情
     */
    public function checkpointDetail(array $where)
    {
        $detail = CheckpointRepository::get_where_one($where);
        $type = self::checkpointType();

        if ($detail) {
            return ['detail' => $detail->toarray(), 'type' => $type];
        }
        return ['detail' => [], 'type' => $type];
    }

    /***
     * 检测机构管理员编辑
     */
    public function adminUpdate(array $data, $admin_id)
    {
        try {
            $service = $data['service'];//服务类型
            //$outlay = $data['outlay'];//车检费用
            unset($data['service']);
            //unset($data['outlay']);
            $data['cate'] = 1;
            $res = CheckpointRepository::edit_or_create(['admin_id' => $admin_id], array_filter($data));

            foreach ($service as $k => $val) {
                $val['checkpoint_id'] = $res->id;
                CheckpointServiceTypeRepository::edit_or_create(['id' => $val['id']], $val);//服务类型
            }

            $arr_data = [
              'id' => $res['admin_id'],
              'phone' => $res['phone'],
              'username' => $res['name'],
            ];
            AdminsRepository::edit_one($arr_data);

            return hello_success('编辑成功', $res);
        } catch (Exception $e) {
            return hello_error('编辑失败');
        }
    }

    /**
     * 删除服务类型
     */
    public function delService($id)
    {
        $res = CheckpointServiceTypeRepository::delete_one((int)$id);
        if ($res) {
            return hello_success('删除成功', $res);
        }

        return hello_error('删除失败');
    }


    /**
     * 检测机构列表
     */
    public function checkpointList($data)
    {
        $list = list_page_data(CheckpointRepository::get_list($data));
        $list['type'] = self::checkpointType();
        return $list;
    }

    /**
     * 检测机构类型
     */
    public function checkpointType()
    {
        $type = CheckpointTypeRepository::get_all()->toarray();
        $typeArray = array();
        foreach ($type as $key => $item) {
            $typeArray[$item['id']] = $item['title'];
        }

        return $typeArray;
    }


    /**
     * 删除
     */
    public function del($data)
    {
        return CheckpointRepository::delete_one((int)$data['id']);
    }


    /*******************************************检测机构开放日期*************************************************/


    /**
     * 检测机构开放日期列表
     */
    public function dayLists($n_shop_id,array $data)
    {
        $checkpoint = CheckpointRepository::base_find_one($n_shop_id);
        if ($checkpoint) {
            $data['checkpoint_id'] = $checkpoint->id;
        } else {
            return hello_error('账户不存在');
        }

        $list = CheckpointMakeDateRepository::get_list($data);
        if ($list) {
            $res = $list->toarray();
            return ['data' => $res['data'], 'total' => $res['total']];
        }

        return ['data' => [], 'total' => 0];
    }

    /**
     * 获取已有日期
     */
    public function checkDay($n_shop_id)
    {
        $checkpoint = CheckpointRepository::base_find_one($n_shop_id);
        if ($checkpoint) {
            $where = ['checkpoint_id' => $checkpoint->id];
            $Y = date('Y', time());
            $min = date('Y-m-d', time());
            $max = $Y + 2 . '-12-31';
            $between = [$min, $max];

            $res = CheckpointMakeDateRepository::get_all_between($where, $between);
            if ($res) {
                $array = array();
                foreach ($res as $item) {
                    $array[] = date("Y-m-d", strtotime($item['day']));
                }
                return ['days' => implode(',', $array) . ',', 'max' => $max];
            }
            return ['day' => '', 'max' => $max];

        } else {
            return hello_error('账户不存在');
        }
    }

    /**
     * 添加开放日期
     */
    public function addDay($n_shop_id,$data)
    {
        $checkpoint = CheckpointRepository::base_find_one($n_shop_id);
        if ($checkpoint) {
            $dayed = [];
            if (!empty($data['dayed'])) {
                $dayed = array_filter(explode(',', $data['dayed']));
            }

            if ($data['type'] == '1' && empty($data['day'])) {
                return hello_error('请选择日期范围');
            }
            if ($data['type'] == '2' && empty($data['month'])) {
                return hello_error('请选择年月范围');
            }

            $days = self::mackDay($data['work'], $data['day'], $data['month']);

            $exist = array_intersect($days, $dayed);

            $time = date('Y-m-d H:i:s', time());
            $add_array = [];
            foreach ($days as $key => $value) {
                if (!in_array($value, $exist)) {
                    $add_array[$key]['checkpoint_id'] = $checkpoint->id;
                    $add_array[$key]['day'] = $value;
                    $add_array[$key]['am_time'] = $data['am_time'];
                    $add_array[$key]['am_num'] = $data['am_num'];
                    $add_array[$key]['pm_time'] = $data['pm_time'];
                    $add_array[$key]['pm_num'] = $data['pm_num'];
                    $add_array[$key]['created_at'] = $time;
                    $add_array[$key]['updated_at'] = $time;
                }
            }

            $res = CheckpointMakeDateRepository::add_more($add_array);//开放日期
            if ($res) {
                return hello_success('添加成功', $res);
            }

            return hello_error('添加失败');

        } else {
            return hello_error('账户不存在');
        }
    }

    /**
     * 日期处理
     */
    public function mackDay($work, $strday, $strmonth)
    {
        if ($strday) {
            $days = array_filter(explode('~', $strday));
        }
        if ($strmonth) {
            $days = array_filter(explode('~', $strmonth));
            $days['0'] = $days['0'] . '-' . date('d', time());
        }

        $startTime = strtotime(str_replace(' ', '', $days['0']));
        $endTime = strtotime(str_replace(' ', '', $days['1']));

        $middle = $startTime;

        $date_attay = array();
        if ($work == '1') {
            while ($middle <= $endTime) {
                if ((date('w', $middle) == 6) || (date('w', $middle) == 0)) {
                } else {
                    $date_attay[] = date('Y-m-d', $middle);
                }
                $middle = strtotime('+1 day', $middle);
            }
        } else {
            while ($middle <= $endTime) {
                $date_attay[] = date('Y-m-d', $middle);
                $middle = strtotime('+1 day', $middle);
            }
        }

        return $date_attay;
    }

    /**
     * 删除开放时间
     */
    public function delDate($id)
    {
        $data = CheckpointMakeDateRepository::base_find_one($id);
        if ($data->am_order > 0 || $data->pm_order > 0) {
            return hello_error('已有预约，不能删除');
        }

        $res = CheckpointMakeDateRepository::delete_one((int)$id);
        if ($res) {
            return hello_success('删除成功', $res);
        }

        return hello_error('删除失败');
    }

    /**
     * 列表删除
     */
    public function delDay($data)
    {
        try {
            if ($data <= 0) {
                return hello_error('数据id不能为空');
            }

            $res = CheckpointMakeDateRepository::delete_one((int)$data);
            if ($res === false) {
                return hello_error('操作失败');
            }
            return hello_success('成功');

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 编辑列表
     */
    public function updateDay($input)
    {
        if ($input['id'] <= 0) {
            return hello_error('数据有误');
        }
        $data = CheckpointMakeDateRepository::get_one((array)['id' => $input['id']]);
        if ($data->am_order > 0 || $data->pm_order > 0) {
            return hello_error('已有预约，不能修改');
        }
        $item['id'] = $data['id'];

        if(in_array($input['field'],['am_time','pm_time'])){
            $time = explode(' - ', $input['value']);
            $start = strtotime($time['0']) ?? false;
            $end = strtotime($time['1']) ?? false;

            if ($start === false || $end === false) {
                return hello_error('请输入正确的时间段');
            } else {
                $item[$input['field']] = date('H:i', $start) . ' - ' . date('H:i', $end);
            }

        }
        else{
            $item[$input['field']] = $input['value'];
        }
        $res = CheckpointMakeDateRepository::edit_one((array)$item);
        if ($res == 1) {
            return hello_success('编辑成功');
        }

        return hello_error('编辑失败');
    }
}